<template>

	<view class="task-details-page">
		<!-- 顶部栏 -->

		<!-- 标题和价格 -->
		<view class="header-section">
			<view class="header-row">
				<view class="task-title">{{ taskDetails?.title || '任务标题加载中...' }}</view>
				<view class="task-price">{{ taskDetails?.price || '0.00' }}</view>
			</view>
			<view class="upload-tip">{{taskDetails.is_attachment==1?"需要上传图片":"无需上传图片"}}</view>
			<view class="task-id-row">
				<text class="task-id">#任务ID:{{taskId}}</text>
			</view>
		</view>
		<view class="header-divider"></view>

		<!-- 用户信息 -->
		<view class="user-section">
			<image class="user-avatar" src="/static/logo.png" mode="aspectFit" />
			<view class="user-info">
				<text class="user-name">米多鱼s</text>
				<!-- <view class="official-btn">
					<text class="official-icon">▼</text>
					<text class="official-text">官方发布</text>
				</view> -->
			</view>
		</view>
		<!-- 任务须知及要求 -->
		<view class="section">
			<view>1.任务步骤请您下载文件查看</view>
			<!-- 下载按钮 -->
			<view class="download-section">
				<button class="download-btn" @click="download">下载任务详细流程文件</button>
			</view>
			<view >2.做单前必看如下任务须知及要求1</view>
			<view class="remind-row">
				<view class="circle-num">1</view>
				<text>任务须知及要求1</text>
			</view>
			<view class="section-content">
				<rich-text :nodes="taskDetails.content"></rich-text>
			</view>
		</view>
	</view>

	<view class="footer-btn" @click="submitTask">
		<button class="submit-btn">提交任务</button>
	</view>
</template>

<script setup>
	// 这里可以根据实际需要引入props、api等
	import { ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app';
	import { getTaskDetails } from '@/api/task.js'
	const taskId = ref(0)
	const taskDetails = ref({
		title: '',
		price: '0.00',
		is_attachment: 0,
		id: 0,
		attachment:'',
		content:''
	})
	onLoad((options) => {

		if (options && options.id) {
			taskId.value = parseInt(options.id, 10); // Ensure taskId is a number
			getTaskDetail();
		} else {
			uni.showToast({ title: '任务ID缺失', icon: 'none' });
		}
	})
	// 获取任务详情
	const getTaskDetail = async () => {

		const res = await getTaskDetails(taskId.value).then((res) => {

			Object.assign(taskDetails.value, res)

		}).catch((error) => {
				console.error('获取任务详情失败:', error)
				uni.showToast({ title: '获取任务详情失败', icon: 'none' })
		});
		console.log('任务详情:', taskDetails.value)

	}
	const download = async () => {
	  if (!taskDetails.value.attachment) {
		uni.showToast({ title: '此任务没有附件', icon: 'success' });
		return;
	  }

	  const fileUrl = typeof taskDetails.value.attachment === 'string' ? taskDetails.value.attachment : '';
	  if (!fileUrl) {
		uni.showToast({ title: '附件地址无效', icon: 'none' });
		return;
	  }
    // 提取文件名（不带后缀）
    const fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1, fileUrl.lastIndexOf('.'));
	// 提取后缀名
    const fileExt = fileUrl.split('.').pop().toLowerCase();
		// 第一步：下载文件
		  uni.downloadFile({
		    url: fileUrl,
		    success: (res) => {
		      uni.hideLoading();

		      if (res.statusCode === 200) {
		        // 第二步：保存文件到本地
		         const filePath = res.tempFilePath;
		        // const fileExt = fileUrl.split('.').pop().toLowerCase();
		        //const finalName = `${fileName}.${fileExt}`;

		        // #ifdef MP-WEIXIN
		        // 微信小程序专用保存方式
		        wx.saveFile({
		          tempFilePath: filePath,
		          success: (savedRes) => {
		            const savedFilePath = savedRes.savedFilePath;
		            wx.showModal({
		              title: '保存成功',
		              content: `文件已保存到: ${savedFilePath}`,
		              showCancel: false,
		              success: () => {
		                // 可以在这里调用打开文档的API
		                wx.openDocument({
		                  filePath: savedFilePath,
		                  fileType: fileExt,
						  showMenu: true,
		                  success: () => console.log('打开文档成功'),
		                  fail: (err) => console.error('打开文档失败', err)
		                });
		              }
		            });
		          },
		          fail: (err) => {
		            console.error('保存失败', err);
		            wx.showToast({
		              title: '保存失败',
		              icon: 'none'
		            });
		          }
		        });
		        // #endif

		        // #ifndef MP-WEIXIN
		        // 其他平台的保存方式
		        // uni.saveFile({
		        //   tempFilePath: filePath,
		        //   success: (savedRes) => {
		        //     uni.showToast({
		        //       title: '保存成功',
		        //       icon: 'success'
		        //     });
		        //   },
		        //   fail: () => {
		        //     uni.showToast({
		        //       title: '保存失败',
		        //       icon: 'none'
		        //     });
		        //   }
		        // });
		        // #endif
		      }
		    },
		    fail: (err) => {
		      uni.hideLoading();
		      console.error('下载失败', err);
		      uni.showToast({
            //objct对象转字符串
            title: '下载失败'+ JSON.stringify(err),
		        icon: 'none'
		      });
		    }
		  });
	};

	
	const back = ()=>{
    uni.navigateBack();
	}
	const submitTask = () => {
		let id = taskDetails.value.id;
		if(!id) return false;
		uni.navigateTo({
			url: `/pages/taskDetails/submitTaskDetail/submitTaskDetail?id=${taskDetails.value.id}&is_attachment=${taskDetails.value.is_attachment}&attachment=${taskDetails.value.attachment}&title=${taskDetails.value.title}&price=${taskDetails.value.price}`
  	  	});
	}
</script>

<style  scoped>
	.task-details-page {
		background: #f6f7fb;
		min-height: 100vh;
		padding-bottom: 100rpx;
	}


	.header-section {
		background: #fff;
		padding: 32rpx 24rpx 0 24rpx;
		border-radius: 0 0 20rpx 20rpx;
	}
	.header-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.task-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #222;
		flex: 1;
		line-height: 1.2;
	}
	.task-price {
		color: #ff4d00;
		font-size: 36rpx;
		font-weight: bold;
		margin-left: 24rpx;
	}
	.upload-tip {
		margin-top: 12rpx;
		font-size: 24rpx;
		color: #999;
	}
	.task-id-row {
		margin-top: 30rpx 0;
		padding-bottom: 30rpx;
	}
	.task-id {
		color: #bbb;
		font-size: 30rpx;
	}
	.header-divider {
		height: 2rpx;
		background: #f0f0f0;
		margin: 24rpx 0 0 0;
		width: 100%;
	}
	.user-section {
		display: flex;
		align-items: center;
		padding: 24rpx;
		background: #fff;
		border-radius: 20rpx;
		margin: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.06);
	}
	.user-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 24rpx;
		background: #eaf2ff;
	}
	.user-info {
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
	.user-name {
		font-size: 28rpx;
		color: #222;
		margin-bottom: 8rpx;
	}
	.official-btn {
		display: flex;
		align-items: center;
		background: #ff9800;
		color: #fff;
		border-radius: 24rpx;
		padding: 0 18rpx;
		height: 40rpx;
		font-size: 22rpx;
	}
	.official-icon {
		font-size: 24rpx;
		margin-right: 6rpx;
	}
	.download-section {
		display: flex;
		justify-content: center;
		margin: 24rpx 0;
	}
	.download-btn {
		background: #1976d2;
		color: #fff;
		border-radius: 12rpx;
		font-size: 28rpx;
		padding: 16rpx 40rpx;
		border: none;
	}
	.section {
		background: #fff;
		margin: 0 24rpx 74rpx 24rpx;
		border-radius: 20rpx;
		padding: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.06);
	}
	.section-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #1976d2;
		margin-bottom: 16rpx;
	}
	.section-content text {
		display: block;
		font-size: 24rpx;
		color: #333;
		margin-bottom: 12rpx;
		line-height: 1.7;
	}
	.footer-btn {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100vw;
		background: transparent;
		z-index: 99;
		padding-bottom: env(safe-area-inset-bottom);
	}
	.submit-btn {
		width: 100vw;
		height: 90rpx;
		background: #1976d2;
		color: #fff;
		font-size: 32rpx;
		border-radius: 0;
		border: none;
		margin: 0;
		box-shadow: none;
	}
	.remind-row {
		display: flex;
		align-items: center;
		margin-bottom: 12rpx;
		margin-top: 24rpx;
	}
	.circle-num {
		width: 36rpx;
		height: 36rpx;
		line-height: 36rpx;
		background: #1976d2;
		color: #fff;
		border-radius: 50%;
		text-align: center;
		font-size: 24rpx;
		font-weight: bold;
		margin-right: 12rpx;
		flex-shrink: 0;
	}
	.remind-title {
		font-size: 26rpx;
		color: #222;
		font-weight: bold;
	}
  
</style>
